<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/4
 * Time: 14:38
 */

namespace app\controllers;

use app\lib\Validator;
use app\models\CouponModal;
use app\models\Customer;
use yii;

class CouponController extends ApiBaseController
{
    public function actionValidate()
    {

        if (!yii::$app->request->isPost) {
            return json_encode(['code' => 0, 'msg' => 'method not allowed']);
        }

        $id = yii::$app->request->post('id');
        $customerNum = yii::$app->request->post('customer_num');
        $data = [
            'id' => $id,
            'customer_num' => $customerNum
        ];
        $rules = [
            'id' => 'required',
            'customer_num' => 'required',
        ];
        $re = Validator::validate($data, $rules);
        if (!is_bool($re)) {
            return json_encode(['code' => 0, 'msg' => $re]);
        }
        //获取当前客户信息
        $model = new Customer();
        $re = $model->one('*', ['number' => $customerNum]);
        if (!$re) {
            return json_encode(['code' => 0, 'msg' => '当前客户编号不存在']);
        }

        $user_id = $re['id'];
        $model = new CouponModal();
        $re = $model->one('*', ['user_id' => $user_id, 'number_no' => $id]);
        if (!$re) {
            return json_encode(['code' => 0, 'msg' => '没有该优惠劵']);
        }
        if ($re['is_active'] == 1 && $re['expire_time'] > time()) {
            return json_encode(['code' => 0, 'msg' => $re]);
        }
        return json_encode(['code' => 0, 'msg' => '优惠券以使用或过期']);
    }

    public function actionValid()
    {
        if (!yii::$app->request->isPost) {
            return json_encode(['code' => 0, 'msg' => 'method not allowed']);
        }

        $number = yii::$app->request->post('number');
        //获取当前客户有效优惠券
        //获取当前客户信息
        $model = new Customer();
        $re = $model->one('*', ['number' => $number]);
        if (!$re) {
            return json_encode(['code' => 0, 'msg' => '当前客户编号不存在']);
        }
        $user_id = $re['id'];
        $model = new CouponModal();
        $re = $model->all('*', ['user_id' => $user_id, 'is_active' => 1]);
        if (!$re) {
            return json_encode(['code' => 0, 'msg' => '没有该优惠劵']);
        }
        $arr = [];
        foreach ($re as $v) {
            if ($v['expire_time'] > time()) {
                $arr[] = $v;
            }
        }
        return json_encode(['code' => 1, 'msg' => $arr]);
    }
}